/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.mk.transaction.distributiontooutlet;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterUnit;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.entities.PosTransactionMkDistributionToOutlet;
import com.ronsicecream.pos.entities.PosTransactionMkDistributionToOutletDetail;
import com.ronsicecream.pos.entities.PosTransactionMkWorkOrder;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.mk.transaction.distributiontooutletdetail.DistributionDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author user
 */
public class Distribution extends Page{
    private Field distributionId;
    private Field distributionDistributorBy;
    private Field distributionNumber;
    private Field distributionCost;
    private Field distributionTotal;
    private Field distributionSent;
    private Field distributionUnsent;
    private Field distributionKeel;
    private Field distributionDate;
    private Field distributionDescription;
    private Field distributionTimestamp;
    private Field distributionUserId;
    private Field distributionUnitId;
//    private Field distributionRegionalId;
//    private Field distributionPosUnitId;
    private Field distributionWorkOrderId;

    public Distribution() {
        setTheClass(PosTransactionMkDistributionToOutlet.class);

        setPageDetail(DistributionDetail.class);
        
        distributionId = new Field();
        distributionId.setName("distributionId");
        distributionId.setCaption(" id");
        //distributionId.setInfo("distribution id");
        distributionId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        distributionId.setInputProperties(" size=\"20\"");
        getFields().add(distributionId);

        distributionDistributorBy = new Field();
        distributionDistributorBy.setName("distributionDistributorBy");
        distributionDistributorBy.setCaption("distributor by");
        //distributionDistributorBy.setInfo("distribution distributor by");
        distributionDistributorBy.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionDistributorBy.setInputProperties(" size=\"20\"");
        getFields().add(distributionDistributorBy);

        distributionNumber = new Field();
        distributionNumber.setName("distributionNumber");
        distributionNumber.setCaption("number");
        //distributionNumber.setInfo("distribution number");
        distributionNumber.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionNumber.setInputProperties(" size=\"30\" readonly");
        getFields().add(distributionNumber);

        distributionCost = new Field();
        distributionCost.setName("distributionCost");
        distributionCost.setCaption("cost");
        //distributionCost.setInfo("distribution cost");
        distributionCost.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        distributionCost.setInputProperties(" size=\"20\"");
        getFields().add(distributionCost);

        distributionTotal = new Field();
        distributionTotal.setName("distributionTotal");
        distributionTotal.setCaption("total");
        //distributionTotal.setInfo("distribution total");
        distributionTotal.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        distributionTotal.setInputProperties(" size=\"20\"");
        getFields().add(distributionTotal);

        distributionSent = new Field();
        distributionSent.setName("distributionSent");
        distributionSent.setCaption("Sent");
        //distributionSent.setInfo("distribution unpaid");
        distributionSent.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        distributionSent.setInputProperties(" size=\"20\"");
        getFields().add(distributionSent);

        distributionUnsent = new Field();
        distributionUnsent.setName("distributionUnsent");
        distributionUnsent.setCaption("unsent");
        //distributionUnsent.setInfo("distribution unpaid");
        distributionUnsent.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        distributionUnsent.setInputProperties(" size=\"20\"");
        getFields().add(distributionUnsent);
        
        distributionDate = new Field();
        distributionDate.setName("distributionDate");
        distributionDate.setCaption("date");
        //distributionDate.setInfo("distribution date");
        distributionDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        distributionDate.setInputProperties(" size=\"8\"");
        distributionDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(distributionDate);
        
        distributionDescription = new Field();
        distributionDescription.setName("distributionDescription");
        distributionDescription.setCaption("description");
        //distributionDescription.setInfo("distribution description");
        distributionDescription.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionDescription.setInputProperties(" size=\"20\"");
        distributionDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        distributionDescription.setInputType(Field.INPUT_TEXT_AREA);
        distributionDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(distributionDescription);

        distributionTimestamp = new Field();
        distributionTimestamp.setName("distributionTimestamp");
        distributionTimestamp.setCaption("timestamp");
        //distributionTimestamp.setInfo("distribution timestamp");
        distributionTimestamp.setListProperties(" align=\"center\"  nowrap");
        distributionTimestamp.setInputProperties(" size=\"12\"");
        //distributionTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(distributionTimestamp);

        distributionUserId = new Field();
        distributionUserId.setName("distributionUserId");
        distributionUserId.setCaption("user");
        //posTransactionReceiptFromMainKitchenCollection.setInfo("pos transaction receipt from main kitchen collection");
        distributionUserId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionUserId.setInputProperties(" size=\"20\"");
        getFields().add(distributionUserId);

        distributionUnitId = new Field();
        distributionUnitId.setName("distributionUnitId");
        distributionUnitId.setCaption("unit");
        distributionUnitId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        distributionUnitId.setInputProperties(" size=\"20\"");
        getFields().add(distributionUnitId);

//        distributionRegionalId = new Field();
//        distributionRegionalId.setName("distributionRegionalId");
//        distributionRegionalId.setCaption("regional");
//        distributionRegionalId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
//        distributionRegionalId.setInputProperties(" size=\"20\"");
//        getFields().add(distributionRegionalId);
//
//        distributionPosUnitId = new Field();
//        distributionPosUnitId.setName("distributionPosUnitId");
//        distributionPosUnitId.setCaption("pos unit");
//        distributionPosUnitId.setRequired(true);
//        distributionPosUnitId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
//        distributionPosUnitId.setInputProperties(" size=\"20\"");
//        getFields().add(distributionPosUnitId);
        
        distributionWorkOrderId = new Field();
        distributionWorkOrderId.setName("distributionWorkOrderId");
        distributionWorkOrderId.setCaption("work order");
        distributionWorkOrderId.setRequired(true);
        distributionWorkOrderId.setSelectorLoad(true);
        distributionWorkOrderId.setListProperties(" align=\"left\" width=\"25%\" nowrap");
        distributionWorkOrderId.setInputProperties(" size=\"20\"");
//        distributionWorkOrderId.setSelectorCondition(" t.requestProgress='4'");
        distributionWorkOrderId.getSelectorColumns().add(new String[]{"workOrderNumber", "Number", " align=\"center\" width=\"20%\" nowrap"});
//        returReceiptId.getSelectorColumns().add(new String[]{"receiptTotal", " Total ", "align=\"right\" width=\"10%\""});
        distributionWorkOrderId.getSelectorColumns().add(new String[]{"workOrderQuantity", " Quantity", " align=\"center\" width=\"10%\" nowrap"});
        distributionWorkOrderId.getSelectorColumns().add(new String[]{"workOrderDescription", " Description", "align=\"left\" width=\"60%\""});
        distributionWorkOrderId.setSelectorOrder("t.workOrderNumber");
        getFields().add(distributionWorkOrderId);
        
        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(distributionNumber);
        getFieldsAdd().add(distributionDate);
        getFieldsAdd().add(distributionWorkOrderId);
//        getFieldsAdd().add(distributionRegionalId);
//        getFieldsAdd().add(distributionMainKitchenId);
        getFieldsAdd().add(distributionDistributorBy);
        getFieldsAdd().add(distributionDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(distributionNumber);
        getFieldsEdit().add(distributionDate);
//        getFieldsEdit().add(distributionMainKitchenId);
//        getFieldsEdit().add(distributionRegionalId);
//        getFieldsEdit().add(distributionPosUnitId);
        getFieldsEdit().add(distributionDistributorBy);
        getFieldsEdit().add(distributionDescription);

        getFieldsList().clear();
        getFieldsList().add(distributionNumber);
        getFieldsList().add(distributionDate);
        getFieldsList().add(distributionUnitId);
//        getFieldsList().add(distributionRegionalId);
        getFieldsList().add(distributionWorkOrderId);
        getFieldsList().add(distributionTotal);
        getFieldsList().add(distributionSent);
        getFieldsList().add(distributionUnsent);
//        getFieldsList().add(distributionPosUnitId);
        getFieldsList().add(distributionDescription);
//        getFieldsList().add(distributionProgress);

        getFieldsView().clear();
        getFieldsView().add(distributionDate);
        getFieldsView().add(distributionNumber);
        getFieldsView().add(distributionUserId);
        getFieldsView().add(distributionUnitId);
//        getFieldsView().add(distributionRegionalId);
        getFieldsView().add(distributionTotal);
//        getFieldsView().add(distributionPaid);
//        getFieldsView().add(distributionUnpaid);
        getFieldsView().add(distributionKeel);
        getFieldsView().add(distributionDescription);
//        getFieldsView().add(distributionPosUnitId);
        getFieldsView().add(distributionTimestamp);
        
        
        setExportList(getClass().getResourceAsStream("DistributionList.jasper"));
        setExport(getClass().getResourceAsStream("Distribution.jasper"));
        
        setController(new Controller(this) {
            @Override
            public void beforeInsert(Object data, List list) {
                PosTransactionMkDistributionToOutlet distr = (PosTransactionMkDistributionToOutlet) data;
                EntityManager em = getEntityManager();
                distr.setDistributionNumber(generate());
                distr.setDistributionUnitId(getCurrentUnit());
                distr.setDistributionUserId(getCurrentUser());
                distr.setDistributionTimestamp(Utility.getTimestamp());
            }

            @Override
            public void afterInsert(Object data, List list) {
                EntityManager em = getEntityManager();
                try{
                    em.getTransaction().begin();
                    PosTransactionMkDistributionToOutlet distribution = (PosTransactionMkDistributionToOutlet) data;
                    PosTransactionMkWorkOrder wo = distribution.getDistributionWorkOrderId();
                    distribution.setDistributionRegionalId(wo.getWorkOrderRegionalId());
                    
//                    PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
//                        + " WHERE t.unitUnitTypeId.unitTypeId=3 "
//                        + " AND t.unitUnitId.unitId="+getCurrentUnit().getUnitId() 
//                        + " AND t.unitRegionalId.regionalId="+distribution.getDistributionRegionalId().getRegionalId()
//                            )
//                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
                
                    BigDecimal total = BigDecimal.ZERO;
                    BigDecimal totalQuantity = BigDecimal.ZERO;
                    for (Object detail : list) {
                        PosTransactionMkDistributionToOutletDetail distributionDetail = (PosTransactionMkDistributionToOutletDetail) detail;
                        PosMasterItemStock stock = Item.getStockItem(em, distributionDetail.getDistributionDetailItemId(),getCurrentUnit());
                        PosTransactionItemStock item = new PosTransactionItemStock();
                        item.setItemStockId(Sequence.next(item));
                        item.setItemStockItemId(distributionDetail.getDistributionDetailItemId());
//                        item.setItemStockRegionalId(posunit.getUnitRegionalId());
//                        item.setItemStockPosUnitId(posunit);
//                        item.setItemStockStatusId(statusGood);
                        item.setItemStockType("$");
                        item.setItemStockLast(stock.getItemStockValue());
                        item.setItemStockValue(distributionDetail.getDistributionDetailQuantity());
                        item.setItemStockCurrent(stock.getItemStockValue().subtract(item.getItemStockValue()));
                        item.setItemStockUnitId(getCurrentUnit());
                        item.setItemStockUserId(getCurrentUser());
                        item.setItemStockTimestamp(Utility.getTimestamp());
                        em.persist(item);
                        stock.setItemStockValue(item.getItemStockCurrent());
                        stock.setItemStockTimestamp(distribution.getDistributionTimestamp());
                       
                        total = total.add(distributionDetail.getDistributionDetailPrice().multiply(distributionDetail.getDistributionDetailQuantity()));
                        totalQuantity=totalQuantity.add(distributionDetail.getDistributionDetailQuantity());
                        distributionDetail.setDistributionDetailSent(BigDecimal.ZERO);
                        distributionDetail.setDistributionDetailUnsent(distributionDetail.getDistributionDetailQuantity());
                    }
                    distribution.setDistributionTotal(total);
                    distribution.setDistributionQuantity(totalQuantity);
                    distribution.setDistributionSent(BigDecimal.ZERO);
                    distribution.setDistributionUnsent(totalQuantity);
                    em.getTransaction().commit();
                }catch(Exception e){
                    System.out.println("Errrr :"+e);
                }
                
            }
            
            
        });
    }
    
   
    
    @Override
    public void beforeAdd() {
        distributionNumber.setDefaultValue(generate());
    }
    
     public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionMkDistributionToOutlet rec = (PosTransactionMkDistributionToOutlet) getEntityManager().createQuery("SELECT t FROM PosTransactionMkDistributionToOutlet t "
                    + "WHERE t.distributionNumber LIKE '%/" + unitCode + "/Rons/DIST-Outlet/%/" + year + "' "
                    + "ORDER BY t.distributionTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(rec.getDistributionNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/Rons/DIST-Outlet/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/Rons/DIST-Outlet/" + month + "/" + year;
    }
}
